<?php

namespace app\api\controller;

use app\model\Config;
use think\Controller;
use think\facade\Cache;
use think\facade\Env;
use think\Request;
use app\model\Order;
use app\model\ProductOrder;
use app\service\PayService;
use think\Response;

class User extends Controller
{
    protected $middleware = [
        'check' => [
            'except' => ['login', 'courseNotify', 'productNotify','productRefundNotify']
        ]
    ];

    public function login(Request $request)
    {
        $app_id = Config::getConfigValue('app_id');
        $app_secret = Config::getConfigValue('app_secret');
        $code = $request->get('code', '', 'trim');
        $admin_id = $request->get('admin_id', 0, 'intval');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $app_id . '&secret=' . $app_secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $json = file_get_contents($url);
        $json = json_decode($json, true);
        if (isset($json['openid'])) {
            $user = Db('user')->where('openid', $json['openid'])->find();
            if ($user) {
                $token = $this->getRandId(16);
                $param = ['token' => $token];
                if($admin_id != 0 && $user['admin_id'] == 0){
                    $param['admin_id'] = $admin_id;
                }
                if (!Db('user')->where('user_id', $user['user_id'])->update($param)) {
                    return ['code' => 2, 'msg' => '登录失败'];
                } else {
                    return ['code' => 0, 'data' => ['token' => $token]];
                }
            } else {
                $data = array();
                $data['avatar'] = '';
                $data['nickname'] = '';
                $data['admin_id'] = $admin_id;
                $data['openid'] = $json['openid'];
                $data['unionid'] = isset($json['unionid']) ? $json['unionid'] : '';
                $data['token'] = $this->getRandId(16);
                $data['create_time'] = date('Y-m-d H:i:s');
                if (Db('user')->insert($data)) {
                    return ['code' => 0, 'data' => ['token' => $data['token']]];
                } else {
                    return ['code' => 2, 'msg' => '登录失败'];
                }
            }
        } else {
            return ['code' => 2, 'msg' => '登录失败'];
        }
    }

    public function saveUserInfo(Request $request)
    {
        $avatar = $request->post('avatar');
        $nickname = $request->post('nickname');
        $param['avatar'] = $avatar;
        $param['nickname'] = $nickname;
        if (false === Db('user')->where(['user_id' => $request->user['user_id']])->update($param)) {
            return ['code' => 2, 'msg' => '服务器繁忙，请少稍后再试'];
        } else {
            return ['code' => 0, 'msg' => '保存成功'];
        }
    }

    public function getUserInfo(Request $request)
    {
        $user = $request->user;
        if ($user['admin_id']) {
            $user['admin_name'] = Db('admin')->where('admin_id', $user['admin_id'])->value('nickname');
        }
        return ['code' => 0, 'data' => $user];
    }

    public function guestBook(Request $request)
    {
        $content = $request->post('content', '', 'trim');
        $phone = $request->post('phone', '', 'trim');
        $images = $request->post('images', '', 'trim');
        if ($content == '') {
            return ['code' => 2, 'msg' => '请填写反馈意见'];
        }
        if ($phone == '') {
            return ['code' => 2, 'msg' => '请填写联系电话'];
        }
        $data = [
            'content'=>$content,
            'phone'=>$phone,
            'images'=>$images,
            'create_time'=>date("Y-m-d H:i:s")
        ];
        $res = Db('guestBook')->insert($data);
        if ($res) {
            return ['code' => 0, 'msg' => '反馈成功！'];
        } else {
            return ['code' => 2, 'msg' => '反馈失败'];
        }
    }

    public function medal(Request $request)
    {
        $list = Db('user_medal')
            ->where('user_id', $request->user['user_id'])
            ->where('create_time','lt', date('Y-m-d H:i:s'))
            ->select();
        return ['code' => 0, 'data' => $list];
    }

    public function myShare(Request $request)
    {
        $image = imagecreatetruecolor(750,1214);
        $head_img = imagecreatefromjpeg($request->user['avatar']);
        $head_img_info = getimagesize($request->user['avatar']);
        imagecopyresized($image,$head_img,292,462,0,0,170,170,$head_img_info[0],$head_img_info[1]);
        imagedestroy ($head_img);
        $page_image = $this->getShareImage($request->user['admin_id']);
        $page_image_info = getimagesize($page_image);
        $page_image = imagecreatefromjpeg($page_image);
        imagecopyresized($image,$page_image,291,814,0,0,169,169,$page_image_info[0],$page_image_info[1]);
        imagedestroy ($page_image);
        $share = imagecreatefrompng('./static/images/share.png');
        imagecopyresampled($image,$share,0,0,0,0,750,1214,750,1214);
        $black = imagecolorallocate($image, 255, 255, 255);
        $leng = mb_strlen($request->user['nickname']) * 12;
        imagefttext ($image , 18 ,0 , 375-$leng, 686 , $black ,Env::get('root_path').'public/static/font/pingfang.ttf', $request->user['nickname']);
        ob_start();
        imagepng($image);
        $content = ob_get_clean();
        imagedestroy($image);
        return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');
    }

    private function getShareImage($admin_id){
        $path = 'uploads/pageImage/'.$admin_id.'.jpg';
        if(!is_file($path)){
            $access_token = $this->getAccessToken();
            $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$access_token;
            $data = ['path'=>'pages/index/index?id='.$admin_id];
            $image = $this->post($url,json_encode($data));
            file_put_contents($path,$image);
        }
        return $path;
    }

    private function post($url, $data = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode == 200) {
            return $tmpInfo;
        } else {
            return '';
        }
    }

    private function getAccessToken(){
        $access_token = Cache::get('access_token');
        if(!$access_token){
            $app_id = Config::getConfigValue('app_id');
            $app_secret = Config::getConfigValue('app_secret');
            $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$app_id.'&secret='.$app_secret);
            $res = json_decode($res,true);
            Cache::set('access_token',$res['access_token'],$res['expires_in']);
            return $res['access_token'];
        }else{
            return $access_token;
        }
    }

    public function getCourseOrderList(Request $request)
    {
        $page = $request->get('page', 1, 'intval');
        $list = Db('order')
            ->alias('o')
            ->join('course c', 'o.course_id = c.course_id', 'LEFT')
            ->where('o.user_id', $request->user['user_id'])
            ->where('o.status', 1)
            ->order('o.create_time desc')
            ->page($page, 10)
            ->field('o.*,c.start_time,c.end_time,c.address as course_address')
            ->select();
        return ['code' => 0, 'data' => $list];
    }

    public function getCourseOrderInfo(Request $request)
    {
        $order_id = $request->get('order_id', 0, 'intval');
        $info = Order::getOrderInfo($order_id);
        return ['code' => 0, 'data' => $info];
    }

    public function courseOrderPay(Request $request)
    {
        $order_id = $request->get('order_id', 0, 'intval');
        $num = $request->get('num', 1, 'intval');
        $info = Order::getOrderInfo($order_id);
        if ($info) {
            if ($info['user_id'] != $request->user['user_id']) {
                return ['code' => 1, 'msg' => '系统错误，请稍后再试'];
            }
            $info['price'] = $info['course_price'] * $num;
            if (Db('order')->where('order_id', $order_id)->update(['price' => $info['price'], 'num' => $num]) !== false) {
                $weixinpay = new PayService('wechat');
                $info['notify'] = Cache::remember('app_host', Config::getConfigValue('app_host')) . '/api/user/courseNotify';
                $info['openid'] = $request->user['openid'];
                $pay_code = $weixinpay->payCode($info);
                if ($pay_code === false) {
                    return ['code' => 1, 'msg' => '系统错误，请稍后再试'];
                } else {
                    return ['code' => 0, 'data' => $pay_code];
                }
            } else {
                return ['code' => 1, 'msg' => '系统错误，请稍后再试'];
            }
        } else {
            return ['code' => 1, 'msg' => '系统错误，请稍后再试'];
        }
    }

    public function courseNotify()
    {
        $service = new PayService('wechat');
        $return = $service->respond();
        if ($return['order']) {
            $info = Db('order')->where('transaction', $return['order'])->find();
            if ($info) {
                Order::setStatus($info['order_id'], 1);
            }
        }
        return Response::create($return['msg'], 'html');
    }

    public function getProductOrderList(Request $request)
    {
        $page = $request->get('page', 1, 'intval');
        $status = $request->get('status', 1, 'intval');
        $productOrder = Db('productOrder')->where('user_id', $request->user['user_id']);
        if ($status == 1) {
            $productOrder->where('status', 'gt', 0);
        } else {
            $productOrder->where('status', -1);
        }
        $list = $productOrder->order('create_time desc')
            ->page($page, 10)
            ->select();
        return ['code' => 0, 'data' => $list];
    }

    public function getProductOrderInfo(Request $request)
    {
        $order_id = $request->get('order_id', 0, 'intval');
        $info = ProductOrder::getOrderInfo($order_id);
        return ['code' => 0, 'data' => $info];
    }

    public function productOrderPay(Request $request)
    {
        $order_id = $request->get('order_id', 0, 'intval');
        $type = $request->get('type', 1, 'intval');
        $info = ProductOrder::getOrderInfo($order_id);
        if ($info) {
            if ($info['user_id'] != $request->user['user_id']) {
                return ['code' => 1, 'msg' => '系统错误，请稍后再试'];
            }
            $product = Db('product')->where('product_id', $info['product_id'])->find();
            if ($info['status'] != 2 && ((time() - strtotime($info['create_time'])) > $product['validity_day'] * 24 * 60 * 60)) {
                return ['code' => 1, 'msg' => '订单已过优惠期'];
            }
            if ($info['status'] == 0 && $type == 2) {
                $info['price'] = $product['deposit'];
                Db('productOrder')->where('order_id', $order_id)->update(['price' => $info['price']]);
            } elseif ($info['status'] == 1) {
                $info['price'] = round($info['product_price'] - $info['price'], 2);
            }
            $weixinpay = new PayService('wechat');
            $info['notify'] = Cache::remember('app_host', Config::getConfigValue('app_host')) . '/api/user/productNotify';
            $info['openid'] = $request->user['openid'];
            $pay_code = $weixinpay->payCode($info);
            if ($pay_code === false) {
                return ['code' => 1, 'msg' => '系统错误，请稍后再试'];
            } else {
                return ['code' => 0, 'data' => $pay_code];
            }
        } else {
            return ['code' => 1, 'msg' => '系统错误，请稍后再试'];
        }
    }

    public function productNotify()
    {
        $service = new PayService('wechat');
        $return = $service->respond();
        if ($return['order']) {
            $info = Db('productOrder')->where('transaction', $return['order'])->find();
            if ($info) {
                $status = $info['price'] == $info['product_price'] || ($info['status'] == 1 && $info['transaction_id'] != $return['transaction_id']) ? 2 : 1;
                ProductOrder::setStatus($info['order_id'], $status);
                Db('productOrder')->where('transaction', $return['order'])->update(['transaction_id'=>$return['transaction_id']]);
            }
        }
        return Response::create($return['msg'], 'html');
    }

    public function productRefundNotify()
    {
        $service = new PayService('wechat');
        $return = $service->refundRespond();
        if ($return['order']) {
            $info = Db('productOrder')->where('transaction', $return['order'])->find();
            if ($info) {
                ProductOrder::setStatus($info['order_id'], -1);
            }
        }
        return Response::create($return['msg'], 'html');
    }

    public function upload(Request $request)
    {
        $image = $request->file('image');
        $num = Db('attachment')->where('user_id', $request->user['user_id'])->where('create_time', 'gt', date('Y-m-d H:i:s', time() - 60 * 60))->count();
        if ($num > 6) {
            return ['code' => 4, 'msg' => '上传过于频繁'];
        }
        $info = $image->validate(['size' => 10485760, 'ext' => 'jpg,jpeg,png,gif'])->move('./uploads');
        if (!$info) {
            return ['code' => 3, 'msg' => '图片上传失败'];
        }
        $image_src = 'uploads/' . str_replace(DIRECTORY_SEPARATOR, '/', $info->getSaveName());
        $data = [
            'user_id' => $request->user['user_id'],
            'name' => $info->getFilename(),
            'size' => $info->getSize(),
            'path' => $image_src,
            'create_time' => date('Y-m-d H:i:s')
        ];
        Db('attachment')->insert($data);
        return ['code' => 0, 'data' => $image_src, 'msg' => '上传成功'];
    }

    private function getRandId($length)
    {
        $pattern = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        $rand_str = '';
        for ($i = 0; $i < $length; $i++) {
            $rand_str .= $pattern{mt_rand(0, strlen($pattern) - 1)};    //生成php随机数
        }
        return $rand_str;
    }
}